<script setup>
import { defineEmits, ref } from 'vue'
import {saveApi, updateApi,levelApi} from "../../../api/role";
import {ElMessage} from "element-plus";
//定义事件--父级
const emit = defineEmits(['flush']);
// 表单数据
const formData = ref({
  id:0,
  name: '',
  info: '',
  level: 0,
  parentId: 0
})
// 抽屉状态
const state = ref(false)
//如果角色等级为二级或三级，那么就需要查询上级角色列表
const changeLevel=(e)=>{
  console.log(e);
  if(e>1){
    levelApi({level:e-1}).then(r=>{
      roles.value=r.data;
    })
  }else {
  }

}
const roles=ref([])

const addRole=async ()=>{
  console.log("id  "+formData.value.id)
  let isadd=formData.value.id==0||formData.value.id==undefined
  let r;
  if(isadd) {
    //新增
    //修改
    r=await saveApi(formData.value)
  }else {
    r = await updateApi(formData.value)
  }
  if(r.code==0){
    ElMessage({
      type: 'success',
      message: isadd?'新增角色成功':'修改角色成功'})
    state.value=false
    emit('flush')
  }else {
    ElMessage.error(r.data)
  }
}
// 暴露
defineExpose({
  state,
  formData
})

</script>
<template>
  <!-- 抽屉 -->
  <el-drawer
    v-model="state"
    :title="formData.id!=undefined ? '编辑角色' : '添加角色'"
    direction="rtl"
    :before-close="() => (state = false)"
  >
    <el-form v-if="state" size="large" label-width="80" :model="formData">
      <el-form-item label="角色名称">
        <el-input type="text" placeholder="请输入角色名称" v-model="formData.name" />
      </el-form-item>
      <el-form-item label="角色等级">
        <el-radio-group v-model="formData.level" class="ml-4" @change="changeLevel">
          <el-radio label="1" size="large">一级</el-radio>
          <el-radio label="2" size="large">二级</el-radio>
          <el-radio label="3" size="large">三级</el-radio>
          <el-radio label="4" size="large">四级</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上级角色" v-show="formData.level!=1">
       <el-select v-model="formData.parentId">
         <el-option v-for="r in roles" :key="r.id" :label="r.name" :value="r.id"></el-option>
       </el-select>
      </el-form-item>

      <el-form-item label="角色说明">
        <el-input type="textarea" v-model="formData.info" placeholder="请输入说明信息" :rows="3" />
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" @click="addRole">确定</el-button>
        <el-button type="default" @click="state = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <!-- 抽屉 -->
</template>
<style lang="scss" scoped></style>
